package com.atguigu.yygh.msn.controller;

import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.msn.service.MsmService;
import com.atguigu.yygh.msn.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msn")
@Api(tags = "手机验证码")
public class MsmApiController {


     @Autowired
    private MsmService  msmService;

     @Autowired
     private RedisTemplate<String,String> redisTemplate;


     //发送手机验证码
     @GetMapping("send/{phone}")
    @ApiOperation(value = "发送手机验证码")
    public Result  send(@PathVariable String phone){

          //从redis获取验证码，如果获取到，返回ok
         //key  手机号 value验证码
         String code = redisTemplate.opsForValue().get(phone);
      if(!StringUtils.isEmpty(code)){

          redisTemplate.opsForValue().set(phone,code,3, TimeUnit.MINUTES);
          code= RandomUtil.getSixBitRandom();
          return Result.ok();
//        Boolean  isSend  =   msmService.send(phone,code);
//          if(isSend==true){
//              redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);
//
//              return  Result.ok();
//          }else{
//
//              return Result.fail().message("发送短信失败");
//          }

      }
         //如果从redis获取不到
         //生成验证码，通过整合短信服务进行发送
       code= RandomUtil.getSixBitRandom();
   //   Boolean  isSend  =   msmService.send(phone,code);
         //生成验证码放到redis里面，设置有效时间
         redisTemplate.opsForValue().set(phone,code,3, TimeUnit.MINUTES);

         return  Result.ok();
//         if(isSend==true){
//
//         }else{
//
//             return Result.fail().message("发送短信失败");
//         }


     }

}
